<template>
  <div>
    <a-alert v-if="title === '确认到岗' && !this.confirmedPost" message="批量到岗时，填写的数据将覆盖选中员工的旧数据" banner />
    <inTemplateForm
      class="pt24"
      ref="basic"
      :dataSource="basicData"
      :dynamicData="empInfoDynamicData"
      :formFields="basicFormJson.fields"
      :sortedKeys="basicFormJson.sortedKeys"
      :formConfig="{}"
      :remove="remove"
      :lookShow="lookShow"
      @onRemove="onRemove"
      @cancel="cancel"
      @change="dynamicChange"
      @customValueChange="onCustomValueChange"
    />
  </div>
</template>

<script>
const additionalArr = [
  {
    companyId: null,
    dropDownEnumList: null,
    fieldCode: "turnStraightDate",
    fieldName: "预计转正日期",
    fieldType: 3,
    gmtCreate: null,
    gmtModified: null,
    id: null,
    isDefault: false,
    isEdit: 1,
    isNecessary: true,
    isOpen: true,
    isRequired: true,
    moduleCode: null,
    moduleName: null,
    sort: 159,
    templateId: null
  },
  {
    companyId: null,
    dropDownEnumList: null,
    fieldCode: "probationDays",
    fieldName: "试用期",
    fieldType: 5,
    gmtCreate: null,
    gmtModified: null,
    id: null,
    isDefault: false,
    isEdit: 1,
    isNecessary: true,
    isOpen: true,
    isRequired: true,
    moduleCode: null,
    moduleName: null,
    sort: 158,
    templateId: null
  }
];
const joinDateDefaultItem = {
  companyId: null,
  dropDownEnumList: null,
  fieldCode: "joinDate",
  fieldName: "入职日期",
  fieldType: 3,
  gmtCreate: null,
  gmtModified: null,
  id: null,
  isDefault: false,
  isEdit: 1,
  isNecessary: true,
  isOpen: true,
  isRequired: false,
  moduleCode: null,
  moduleName: null,
  sort: 152,
  templateId: null
};
import { formatDateDefault, afterTime } from "@/utils/index";
import inTemplateForm from "./inTemplateForm";
import { selectOpenTemplate as selectOpenTemplateReq, selectOpenTemplate3Req } from "../api.js";
import { basicsPages } from "./dynamic";
import { mapState } from "vuex";
import moment from "moment";
export default {
  components: { inTemplateForm },
  props: {
    moduleCode: {
      type: String,
      default: ""
    },
    title: {
      type: String,
      default: ""
    },
    confirmedPost: {
      type: Boolean,
      default: false
    },
    outEmpDetail: {
      type: Object,
      default: () => {}
    },
    checkInAllValue: {
      type: Object,
      default: () => {}
    },
    checkInIdForm: {
      type: String,
      default: ""
    },
    isQuerendaogang: {
      type: Boolean,
      default: false
    },
    isBatchJoin: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      lookShow: false,
      additionalArr,
      joinDateDefaultItem,
      remove: false,
      customTemplateFieldVOList: [],
      editListKeys: [],
      templateList: [],
      listDefaultVal: [],
      visibleField: false,
      basicData: {},
      empTrainData: null,
      basicFormJson: { editable: true },
      form: this.$form.createForm(this, { name: "horizontal_login" })
    };
  },
  computed: {
    ...mapState(["company"]),
    empInfoDynamicData() {
      return {
        depNameDynamic: this.company.companyDefSource,
        positionOptions: this.company.companyPosSource
      };
    }
  },
  watch: {
    title: {
      handler(val) {
        if (val === "编辑") {
          this.remove = true;
        } else if (val === "查看") {
          this.lookShow = true;
        } else if (val === "确认到岗") {
          this.remove = false;
        } else {
          this.remove = false;
        }
        this.selectOpenTemplate();
      },
      immediate: true,
      deep: true
    },
    checkInAllValue: {
      handler(val) {
        if (val && Object.keys(val).length > 0) {
          this.selectOpenTemplate();
        }
      },
      deep: true
    }
  },
  created() {},
  methods: {
    cancel() {
      this.$emit("cancelForm");
    },
    GetDateDiff(time1, time2) {
      time1 = new Date(time1); // 转换为中国标准时间
      time2 = new Date(time2);
      time1 = time1.getTime(); // 转换为时间戳
      time2 = time2.getTime();
      var runTime = (time2 - time1) / 1000; // 开始得出时间差,然后计算
      var year = Math.floor(runTime / 86400 / 365);
      runTime = runTime % (86400 * 365);
      var month = Math.floor(runTime / 86400 / 30);
      runTime = runTime % (86400 * 30);
      var day = Math.floor(runTime / 86400);
      runTime = runTime % 86400;
      var hour = Math.floor(runTime / 3600);
      runTime = runTime % 3600;
      var minute = Math.floor(runTime / 60);
      runTime = runTime % 60;
      var second = runTime;
      return year + "," + month + "," + day;
    },
    onCustomValueChange(value, key) {
      if (key === "formalType" && value) {
        //  员工状态
        if (value === "1") {
          this.customTemplateFieldVOList.map((z) => {
            if (z.fieldCode === "turnStraightDate" || z.fieldCode === "probationDays") {
              z.isOpen = true;
            }
          });
          this.getListCompanyModuleCodes(this.customTemplateFieldVOList);
          this.$set(this.basicFormJson.fields.probationDays.decorator, "rules", [{ required: true, message: "请选择预计转正日期" }]);
          this.$set(this.basicFormJson.fields.turnStraightDate.customize, "disabled", true);
          this.$set(this.basicFormJson.fields.turnStraightDate.decorator, "rules", []);
          this.$set(this.basicFormJson.fields.probationDays.customize, "formatter", (value) => `${value}天`);
        } else {
          const theFormalType = this.customTemplateFieldVOList.filter((item) => item.isOpen && item.fieldCode === "formalType");
          this.customTemplateFieldVOList.filter((z) => {
            if (z.fieldCode === "probationDays") {
              z.isOpen = false;
            }
            if (z.fieldCode === "turnStraightDate") {
              z.isOpen = theFormalType && theFormalType.length > 0;
            }
          });
          this.getListCompanyModuleCodes(this.customTemplateFieldVOList);
          this.$set(this.basicFormJson.fields.turnStraightDate.customize, "disabled", false);
          this.$set(this.basicFormJson.fields.turnStraightDate.decorator, "rules", [{ required: true, message: "请选择预计转正日期" }]);
        }
      } else if (key === "probationDays") {
        const newTime = afterTime(this.$refs.basic.getFieldValue("joinDate"), value);
        this.$nextTick(() => {
          this.$refs.basic.setFieldsValueShow(this.moment(newTime));
        });
      } else if (key === "joinDate" && this.$refs.basic.getFieldValue("probationDays")) {
        // 入职日期
        const newTime = afterTime(value, this.$refs.basic.getFieldValue("probationDays"));
        this.$nextTick(() => {
          this.$refs.basic.setFieldsValueShow(this.moment(newTime));
        });
      } else if (key === "turnStraightDate") {
        // 预计转正日期
        const joinDate = moment(this.$refs.basic.getFieldValue("joinDate")).format("YYYY-MM-DD");
        const num = this.GetDateDiff(joinDate, value)
          .split(",")
          .find((z) => z < 0);
        if (num) {
          this.$message.error("预计转正日期要大于入职日期,请重新选择预计转正日期");
          this.$nextTick(() => {
            this.$refs.basic.setFieldsValueShow1("turnStraightDate", null);
          });
        }
      } else if (key === "joinDate" && this.$refs.basic.getFieldValue("turnStraightDate")) {
        // 预计转正日期
        const turnStraightDate = moment(this.$refs.basic.getFieldValue("turnStraightDate")).format("YYYY-MM-DD");
        const num = this.GetDateDiff(value, turnStraightDate)
          .split(",")
          .find((z) => z < 0);
        if (num) {
          this.$message.error("预计转正日期要大于入职日期,请重新选择入职日期");
          this.$nextTick(() => {
            this.$refs.basic.setFieldsValueShow1("joinDate", null);
          });
        }
      }
    },
    onRemove() {
      this.$emit("onRemove");
    },
    dynamicChange(value) {
      console.log(value);
      if (value) {
        const dataKeys = []; // 自定义的
        let dataKeysDefauit = {}; // 系统默认
        if (this.title !== "编辑") {
          Object.keys(value).map((z) => {
            if (!isNaN(parseInt(z))) {
              const data = {
                id: z,
                type: this.basicFormJson.fields[z].type,
                fieldName: this.basicFormJson.fields[z].fieldName,
                content: value[z]
              };
              dataKeys.push(data);
            } else {
              dataKeysDefauit = Object.assign({ [z]: value[z] }, dataKeysDefauit);
            }
          });
        } else {
          Object.keys(value).map((z) => {
            const item = this.checkInAllValue.additionalFieldVOList.find((i) => i.fieldId + "" === z);
            if (!isNaN(parseInt(z))) {
              const data = {
                id: item.empAdditionalId,
                fieldId: z,
                type: this.basicFormJson.fields[z].type,
                fieldName: this.basicFormJson.fields[z].fieldName,
                content: value[z]
              };
              dataKeys.push(data);
            } else {
              dataKeysDefauit = Object.assign({ [z]: value[z] }, dataKeysDefauit);
            }
          });
        }
        dataKeys.map((i) => {
          if (i.type === "upload") {
            const elePropType = Object.prototype.toString.call(i.content);
            if (elePropType === "[object String]") {
              if (!i.content.includes("http")) {
                i.content = null;
              }
            } else if (elePropType === "[object Array]") {
              const strJoin = [];
              for (let j = 0; j < i.content.length; j++) {
                if (Object.prototype.toString.call(i.content[j]) === "[object Object]" && i.content[j].url) {
                  strJoin.push(i.content[j].url);
                } else if (Object.prototype.toString.call(i.content[j]) === "[object String]" && i.content[j].includes("http")) {
                  strJoin.push(i.content[j]);
                }
              }
              i.content = strJoin.join(",");
            } else {
              i.content = null;
            }
          }
          if (i.type === "area") {
            i.content = i.content ? i.content + "" : null;
          }
        });
        Object.keys(dataKeysDefauit).map((i) => {
          if (dataKeysDefauit[i] instanceof Array && dataKeysDefauit[i].length !== 0) {
            if (dataKeysDefauit[i][0].url) {
              dataKeysDefauit[i] = dataKeysDefauit[i].map((i) => i.url) + "";
            }
          }
          return i;
        });
        const outEmpDetail = this.outEmpDetail ? this.outEmpDetail : {};
        const data = Object.assign(outEmpDetail, dataKeysDefauit, { addEmpFieldList: dataKeys });
        this.$emit("saveValueChange", data);
      }
    },
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.fieldCode) && res.set(arr.fieldCode, 1));
    },
    selectOpenTemplate() {
      const data = {
        companyId: this.moduleCode === "checkIn" ? "site" : this.$store.state.hr.companyId,
        moduleCode: this.moduleCode
      };
      const req = this.isBatchJoin ? selectOpenTemplate3Req : selectOpenTemplateReq;
      req(data)
        .then((res) => {
          const additionalFieldsListVOS = this.isBatchJoin
            ? []
            : res.data.additionalFieldsListVOS.map((z) => {
                z.fieldCode = z.id;
                return z;
              });
          const data = [...res.data.customTemplateFieldVOList, ...additionalFieldsListVOS];
          data.map((i) => {
            if (i.fieldCode === "formalType") {
              this.additionalArr[0].sort = i.sort + 0.3;
              this.additionalArr[1].sort = i.sort + 0.2;
              this.joinDateDefaultItem.sort = i.sort + 0.1;
            }
          });
          const tempFields = data.filter((item) => item.isOpen).map((item) => item.fieldCode);
          const needDefaultJoinDate = tempFields.includes("formalType") && !tempFields.includes("joinDate");
          this.customTemplateFieldVOList = [
            ...data,
            ...(needDefaultJoinDate ? [this.joinDateDefaultItem] : []),
            ...this.additionalArr
          ].sort((a, b) => {
            return a.sort - b.sort;
          });
          // 加去重
          this.customTemplateFieldVOList.map((z) => {
            if (z.fieldCode === "probationDays") {
              z.isOpen = false;
            }
            if (z.fieldCode === "turnStraightDate") {
              z.isOpen = tempFields.includes("formalType");
            }
          });
          const tempKeys = this.customTemplateFieldVOList.filter((item) => item.isOpen).map((item) => item.fieldCode);
          this.getListCompanyModuleCodes(this.customTemplateFieldVOList);
          if (this.title === "编辑") {
            const status = this.checkInAllValue.status;
            this.checkInAllValue.status =
              status === "4" ? "已入职" : status === "5" ? "已离职" : status === "6" ? "待入职" : status === "7" ? "未到岗" : status;
            this.customTemplateFieldVOList.filter((i) => {
              if (i.fieldCode === "postType") {
                this.onCustomValueChange(this.checkInAllValue.postType, "postType");
              }
              if (i.fieldCode === "formalType") {
                this.onCustomValueChange(this.checkInAllValue.formalType, "formalType");
              }
            });

            this.getEmpFieldValues(this.checkInAllValue);
          } else if (this.title === "查看") {
            const status = this.checkInAllValue.status;
            this.checkInAllValue.status =
              status === "4" ? "已入职" : status === "5" ? "已离职" : status === "6" ? "待入职" : status === "7" ? "未到岗" : status;
            if (tempKeys.includes("formalType")) {
              this.onCustomValueChange(this.checkInAllValue.formalType, "formalType");
            }
            if (tempKeys.includes("postType")) {
              this.onCustomValueChange(this.checkInAllValue.postType, "postType");
            }
            this.getEmpFieldValues(this.checkInAllValue);
          } else if (this.title === "确认到岗" && !this.confirmedPost) {
            this.customTemplateFieldVOList.map((z) => {
              if (z.fieldCode === "phone") {
                z.isOpen = false;
              }
              if (z.fieldCode === "idCard") {
                z.isOpen = false;
              }
            });
            this.getListCompanyModuleCodes(this.customTemplateFieldVOList);
            this.$set(this.basicFormJson.fields.name.customize, "disabled", true);
            this.$nextTick(() => {
              let name = "";
              if (this.outEmpDetail.arr.length === 1) {
                name = this.outEmpDetail.arr[0].name;
              } else {
                name = `${this.outEmpDetail.arr[0].name}等${this.outEmpDetail.arr.length}人`;
              }
              this.$refs.basic.setFieldsValueShow1("name", name);
            });
          } else {
            if (this.outEmpDetail && JSON.stringify(this.outEmpDetail) !== "{}") {
              const additionalFieldVOList = this.outEmpDetail.additionalFieldVOList ? this.outEmpDetail.additionalFieldVOList : [];
              let dataq = {};
              additionalFieldVOList.map((z) => {
                const dd = this.customTemplateFieldVOList.find((y) => y.fieldName === z.fieldName && y.fieldType === z.fieldType);
                if (dd) {
                  dataq = Object.assign(dataq, { [dd.fieldCode]: z.content });
                }
              });
              this.getEmpFieldValues(Object.assign(this.outEmpDetail, dataq));
              if (tempKeys.includes("formalType")) {
                this.onCustomValueChange(this.outEmpDetail.formalType, "formalType");
              }
              if (tempKeys.includes("postType")) {
                this.onCustomValueChange(this.outEmpDetail.postType, "postType");
              }
              if (this.confirmedPost) {
                this.$set(this.basicFormJson.fields.name.customize, "disabled", true);
                this.$set(this.basicFormJson.fields.idCard.customize, "disabled", true);
                this.$set(this.basicFormJson.fields.phone.customize, "disabled", true);
              }
            } else {
              const data = this.basicFormJson.sortedKeys.reduce((res, key) => {
                res[key] = null;
                return res;
              }, {});
              data["formalType"] = "2";
              data["joinDate"] = formatDateDefault();
              data["probationDays"] = 0;
              data["turnStraightDate"] = formatDateDefault();
              this.getEmpFieldValues(data);
            }
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 获取展示数据
    getListCompanyModuleCodes(element) {
      this["basicFormJson"] = {
        editable: false,
        fields: {},
        sortedKeys: {}
      };
      const { fields, fieldKeys } = basicsPages("basic", [...(element && element.length > 0 ? element : [])]);
      this["basicFormJson"].fields = fields;
      this["basicFormJson"].sortedKeys = fieldKeys;
      this.list = this["basicFormJson"].sortedKeys;
    },
    // 各项数据源
    getEmpFieldValues(moduleCode) {
      for (const key in moduleCode) {
        if (moduleCode[key] === "true") {
          moduleCode[key] = "true";
        }
        if (moduleCode[key] === "false") {
          moduleCode[key] = "false";
        }
      }
      this["basicData"] = moduleCode;
    }
  }
};
</script>
